﻿
namespace USElections.Calendar.Command
{
    using System;
    using System.Windows;
    using System.Windows.Input;
    using Microsoft.Phone.Scheduler;
    using USElections.Calendar.Model;

    /// <summary>
    /// SetReminderCommand class.
    /// </summary>
    public class SetReminderCommand : ICommand
    {
        #region Events
        /// <summary>
        /// CanExecute Changed event.
        /// </summary>
        public event EventHandler CanExecuteChanged;
        #endregion

        #region Public methods
        /// <summary>
        /// Indicates if the command can be executed.
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        /// <returns>True if parameter is set.</returns>
        public bool CanExecute(object parameter)
        {
            if (parameter != null)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Execute command.
        /// </summary>
        /// <param name="parameter">An ElectionsAppointment object.</param>
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                ElectionsAppointment ea = parameter as ElectionsAppointment;

                if (ea != null)
                {
                    Reminder reminder = new Reminder(ea.Id);
                    reminder.BeginTime = ea.StartDate;

                    if (!string.IsNullOrEmpty(ea.Details) && string.Compare(ea.Details, "-", StringComparison.InvariantCulture) == 1)
                    {
                        reminder.Content = ea.Details;
                    }
                    
                    reminder.Title = ea.Subject;
                    reminder.RecurrenceType = RecurrenceInterval.None;
                    reminder.ExpirationTime = reminder.BeginTime.AddDays(1);

                    if (ScheduledActionService.Find(reminder.Name) == null)
                    {
                        try
                        {
                            ScheduledActionService.Add(reminder);

                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("Successfully added reminder");
                            });
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
        #endregion
    }
}
